package com.itheima.reggie.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.JwtUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.damain.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取token
        String token=request.getHeader("Authorization");
        //去除多余部分，再去除两端空格
        token=token.replace("Bearer", "").trim();
       //打印日志
        log.info("token="+token);
        if (StringUtils.isEmpty(token)){
            //如果token为空则报错
            ResultInfo resultInfo=ResultInfo.error("NOTLOGIN");
            String json=new ObjectMapper().writeValueAsString(resultInfo);
            response.getWriter().write(json);
            return false;//禁止通行
        }
//解析token
        try {
            JwtUtil.parseToken(token);
        }catch (Exception e){
            ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");
            String json=new ObjectMapper().writeValueAsString(resultInfo);
            response.getWriter().write(json);
            return false;//禁止通行
        }
        //3，从redis中根据token查询用户信息
        User user= (User) redisTemplate.opsForValue().get("token-"+token);
        if (user==null){
            ResultInfo resultInfo= ResultInfo.error("NOTLOGIN");
            String json=new ObjectMapper().writeValueAsString(resultInfo);
            response.getWriter().write(json);
            return false;//禁止通行
        }
        //4.放行
        //redis中数据续期
        redisTemplate.opsForValue().set("token-"+token,user,1, TimeUnit.DAYS);
        UserHolder.set(user);
        return true;//放行

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
